using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Text;
using System.IO;
using System.Collections;

/// <summary>
/// Summary description for ImageHelper
/// </summary>
namespace SiteECSWeb
{
    public class ImageHelper
    {
        public static void WriteWatermark(System.Drawing.Image image,
          string watermark, Graphics g, Font font)
        {
            //Determine size of watermark to write background
            SizeF watermarkSize = g.MeasureString(watermark, font);

            int xPosition = 10;
            int yPosition = image.Height - (int)watermarkSize.Height - 10;

            //Draw a translucent (alpha = 100) background for watermark
            g.FillRectangle(
                new SolidBrush(Color.FromArgb(100, Color.GhostWhite)),
                new Rectangle(
                    xPosition,
                    yPosition,
                    (int)watermarkSize.Width,
                    (int)watermarkSize.Height));

            //Write watermark
            g.DrawString(watermark,
                font,
                new SolidBrush(Color.Blue), xPosition, yPosition);
        }
        public static void WriteHotlinkMessage(HttpContext context, System.Drawing.Image image,
           string sitename, Graphics g, Font font)
        {
            //If hotlinked, draw hatched overlay
            g.FillRectangle(
                new HatchBrush(
                    HatchStyle.LargeConfetti,
                    Color.FromArgb(90, Color.Blue)),
                new Rectangle(0, 0, image.Width, image.Height));

            //Write our site name in the center of the image
            SizeF siteSize = g.MeasureString(sitename, font);
            g.DrawString(sitename,
                font,
                new SolidBrush(Color.White),
                (image.Width - siteSize.Width) / 2,
                (image.Height - siteSize.Height) / 2);
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
        }
        public static string GetCopyrightYear(System.Drawing.Image image, string defaultValue)
        {
            string value;
            //First try to read copyright (Exif Value 33432)
            if (GetExifString(image, ExifValues.Copyright, out value))
            {
                return GetYear(value, value);
            }
            //Now try Date Taken (Exif Value 36867)
            if (GetExifString(image, ExifValues.DateTimeOriginal, out value))
            {
                string datepart = value.Split(' ')[0];
                datepart = datepart.Replace(':', '/');

                return GetYear(datepart, value);
            }
            return defaultValue;
        }
        public static string GetYear(string dateString, string value)
        {
            DateTime date;
            if (DateTime.TryParse(dateString, out date))
                return date.Year.ToString();
            else
                return value;
        }
        public static bool GetExifString(
            System.Drawing.Image image, ExifValues exifProperty, out string value)
        {
            value = null;
            try
            {
                PropertyItem propertyItem =
                    image.GetPropertyItem((int)exifProperty);
                if (propertyItem != null)
                {
                    value = Encoding.UTF8.GetString(propertyItem.Value)
                        .Trim() as string;
                }
            }
            catch { }
            return !string.IsNullOrEmpty(value);
        }
        public static string GetContentType(FileInfo _fileInfo)
        {
            switch (_fileInfo.Extension.ToUpper())
            {
                case ".GIF":
                    return "image/gif";
                case ".JPG":
                case ".JPEG":
                    return "image/jpeg";
                case ".PNG":
                    return "image/png";
                default:
                    throw new Exception("Invaild Image Type");
                    break;
            }
        }
        public static ImageFormat GetImageFormat(FileInfo _fileInfo)
        {
            switch (_fileInfo.Extension.ToUpper())
            {
                case ".GIF":
                    return ImageFormat.Gif;
                case ".JPG":
                case ".JPEG":
                    return ImageFormat.Jpeg;
                case ".PNG":
                    return ImageFormat.Png;
                default:
                    throw new Exception("Invaild Image Type");
                    break;
            }
        }

        public static Size CalculateDimensions(Size oldSize, int targetSize)
        {
            if (targetSize == 4)
            {
                return oldSize;
            }
            Size newSize = new Size();
            if (oldSize.Height > oldSize.Width)
            {
                newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
                newSize.Height = targetSize;
            }
            else
            {
                newSize.Width = targetSize;
                newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
            }
            return newSize;
        }
        public static PhotoSize GetSizeParam(HttpContext context)
        {
            switch (context.Request.QueryString["Size"])
            {
                case "S":
                    return PhotoSize.Small;
                case "M":
                    return PhotoSize.Medium;
                case "L":
                    return PhotoSize.Large;
                default:
                    return PhotoSize.Original;
            }
            
        }
        public static string GetSizeSting(PhotoSize size)
        {
            string realSize = null;
            switch (size)
            {
                case PhotoSize.Small:
                    realSize = "S";
                    break;
                case PhotoSize.Medium:
                    realSize = "M";
                    break;
                case PhotoSize.Large:
                    realSize = "L";
                    break;
                default:
                    realSize = "O";
                    break;
            }
            return realSize;
        }

        //public static string GetImageHandler(string filePath, PhotoSize imgSize)
        //{
        //    if (string.IsNullOrEmpty(filePath))
        //    {
        //        return string.Empty;
        //    }
        //    else
        //    {
        //        return "~/ImageHandler.ashx?image=" + filePath + "&Size="
        //            + GetSizeSting(imgSize) 
        //            + "&key=" + HotlinkProtection.GetKey() + "";
        //    }
        //}
        public static string SetImgPhotoBookPath(string fileName)
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                if (!fileName.Contains(Globals.Settings.UploadInfo.RootAttachFolder))
                {
                    fileName = Globals.Settings.UploadInfo.RootAttachFolder +
                        fileName;
                }
                return fileName;
            }
            else
            {
                return Globals.Settings.UploadInfo.ImgEmptyBook;
            }
        }
        public static string SetImgPhotoPath(string sessionFileName,
            string folderName, PhotoSize imgSize)
        {
            if (!string.IsNullOrEmpty(sessionFileName))
            {
                if (HttpContext.Current.Session[sessionFileName] != null &&
                    !string.IsNullOrEmpty(folderName))
                {
                    return "~/ImageHandler.ashx?image="
                        + folderName
                        + ((ArrayList)HttpContext.Current.Session[sessionFileName])[0].ToString()
                        + "&Size=" + GetSizeSting(imgSize)
                        + "&key=" + HotlinkProtection.GetKey() + "";
                }
                else
                {
                    if (sessionFileName.IndexOf(@"\\") == -1)
                    {
                        if (imgSize == PhotoSize.Small)
                        {
                            return Globals.Settings.UploadInfo.ImgEmptyPathSmall;
                        }
                        else
                        {
                            return Globals.Settings.UploadInfo.ImgEmptyPathSmall;
                        }
                    }
                    else
                    {
                        return "~/ImageHandler.ashx?image="
                      + sessionFileName
                      + "&Size=" + GetSizeSting(imgSize)
                      + "&key=" + HotlinkProtection.GetKey() + "";
                    }
                }
            }
            else
            {
                return Globals.Settings.UploadInfo.ImgEmptyPathSmall;
            }
        }
        public static string SaveImgPhotointoRealFolder(string sessionFileName,
            string realFolderName)
        {
            string filePath = null; 
            if (HttpContext.Current.Session[sessionFileName] != null)
            {
                try
                {
                    FileInfo fInfo = new FileInfo(
                        HttpContext.Current.Server.MapPath(Globals.Settings.UploadInfo.RootAttachFolder
                        + Globals.Settings.UploadInfo.TempUploadFolder
                        + ((ArrayList)HttpContext.Current.Session[sessionFileName])[0].ToString()));

                    if (fInfo.Exists)
                    {
                        filePath = realFolderName+ 
                            ((ArrayList)HttpContext.Current.Session[sessionFileName])[0].ToString();

                        //FileInfo fInfo2 = new FileInfo(
                        //    HttpContext.Current.Server.MapPath(Globals.Settings.UploadInfo.RootAttachFolder
                        //    + Globals.Settings.UploadInfo.TempUploadFolder
                        //    + filePath));
                        //if (f)
                        //{
                            
                        //}
                        
                        fInfo.MoveTo
                            (HttpContext.Current.Server.MapPath(Globals.Settings.UploadInfo.RootAttachFolder
                            + filePath));
                        HttpContext.Current.Session[sessionFileName] = null;
                    }
                }
                catch (IOException ex)
                {
                    throw;
                }
            }
            return filePath;      
        }
    }
}

